package com.tonghe.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.tonghe.constants.SystemConstants;
import com.tonghe.domain.ResponseResult;
import com.tonghe.enums.AppHttpCodeEnum;
import com.tonghe.exception.SystemException;
import com.tonghe.mapper.UserMapper;
import com.tonghe.service.UploadService;
import com.tonghe.utils.PathUtils;
import com.tonghe.utils.SecurityUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * @date: 2022/3/14- 03- 14- 22:04
 * @author: tonghe
 **/
//@ConfigurationProperties(prefix = "oss")
@Service
@Data
public class OssUploadServiceImpl implements UploadService {

    @Value("${oss.accessKey}")
    private String  accessKey;
    @Value("${oss.secretKey}")
    private String  secretKey;
    @Value("${oss.bucket}")
    private String  bucket;
    @Value("${oss.outSideChain}")
    private String outSideChain;
    @Value("${spring.servlet.multipart.max-request-size}")
    private String maxRequestSize;

    @Autowired
    private UserMapper userMapper;

    /**
    * @description: 上传文件，此处仅限jpg、jpeg、png
    * @param： [img]文件
    * @return： com.tonghe.domain.ResponseResult
    * @author: TongHe
    * @date: 2022/3/17 17:56
    */
    @Override
    public ResponseResult uploadImg(MultipartFile img) throws IOException{
        // TODO 判断文件上传大小
        String filename = img.getOriginalFilename();
        // 对原始文件名进行判断
        if(!filename.endsWith(SystemConstants.UPLOAD_IMAGE_FILE_TYPE1) && !filename.endsWith(SystemConstants.UPLOAD_IMAGE_FILE_TYPE2) && !filename.endsWith(SystemConstants.UPLOAD_IMAGE_FILE_TYPE3)){
            throw new SystemException(AppHttpCodeEnum.CONTENT_NOT_NULL);
        }
        String filePath = PathUtils.generateFilePath(filename);
        String url = uploadOss(img, filePath);
        return ResponseResult.okResult(url);
    }

    /**
    * @description: AliOSS
    * @param： [filePath, inputStream]
    * @return： java.lang.String
    * @author: TongHe
    * @date: 2022/9/24 11:37
    */
    private String uploadFile(String filePath, InputStream inputStream) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "oss-cn-beijing.aliyuncs.com";

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "weqeq";
        String accessKeySecret = "wqeqrqrqwe";
        String bucketName = "sg-blog-oss";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, inputStream);

        // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传字符串。
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
        return "https://"+bucketName+"."+endpoint+"/"+filePath;
    }


    /**
    * @description:
    * @param： [img, filePath]
    * @return： java.lang.String
    * @author: TongHe
    * @date: 2022/3/17 17:56
    */
    private String uploadOss(MultipartFile img , String filePath){

        // 构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(cfg);
        // 2022/3/10/uuid.png
        String key = filePath;

        try {
            InputStream inputStream = img.getInputStream();

            // 创建凭证
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//                System.out.println(putRet.key);
//                System.out.println(putRet.hash);

                // 返回外联
                return outSideChain+key;

            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    // ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return null;
    }

}
